import json
import time

from bot.enterprise_wechat_gpt.config.conf import *
from bot.enterprise_wechat_gpt.util.tair_util import tair_util
from bot.enterprise_wechat_gpt.util.postgre_sql_util import postgre_sql

exist_coupon = {
    "30天免息券（31-61天免息）",
    "11月8折息费折扣券",
    "首贷30天免息劵",
    "贴息30天免息",
    "贴息8折息费折扣券",
    "贴息6折息费折扣券",
    "企微专享30天免息券",
    "企微专享8折息费折扣券",
    "已激活-未首贷企微专享30天免息券",
    "首贷-企微专享单笔年化利率4.5%"
}


# def get_user_info(wx_id):
#     return tair_util.get(f"QW:UserInfo:{wx_id}")


def get_user_info_dict_redis(wx_id) -> dict:
    info = tair_util.get(f"QW:UserInfo:{wx_id}")
    if info is None:
        return {"coupon": [], "tag": {}}
    return json.loads(info)


def get_user_info_dict(wx_id) -> dict:
    start = time.time()
    with postgre_sql.get_resource() as (cursor, conn):
        cursor.execute(f"select wx_id, agent_id, username, sex, remaining_balance, credit_balance,loan_intention, background_coupon_name, has_coupon, json_data from public.wechat_user_info where wx_id = '{wx_id}' order by create_time desc limit 1")
        result = cursor.fetchone()
        if result is None:
            return {}
        result = dict(result)
        logging.info(f"wx_id:{wx_id} 查询用户耗时:{time.time() - start}s")
        return result


def set_user_info_to_redis(wx_id, userInfo):
    tair_util.set_expire(f"QW:UserInfo:{wx_id}", userInfo, 3600)


def set_user_info(customer_id, wx_id, agent_id, userInfo: dict):
    username = userInfo.get("username", None)
    if (username is None or username == '') and userInfo.get('tag', {}) == {}:
        logging.warning(f"用户信息为空 不插入数据库 wx_id:{wx_id}")
        return
    set_user_info_to_redis(wx_id, json.dumps(userInfo, ensure_ascii=False, indent=2))
    sex = userInfo.get('tag', {}).get('性别', None)
    remaining_balance = userInfo.get('tag', {}).get('金条剩余额度_实时', None)
    credit_balance = userInfo.get('tag', {}).get('金条授信额度_实时', None)
    loan_intention = userInfo.get('tag', {}).get('金条借贷意向', None)
    background_coupon_name = userInfo.get('coupon', [])[0].get('activityName', None) if userInfo.get('coupon', []) else None
    has_coupon = userInfo.get('tag', {}).get('用户是否有金条优惠券', None)
    json_data = json.dumps(userInfo, ensure_ascii=False, indent=2)
    val = (wx_id, agent_id, username, sex, remaining_balance, credit_balance, loan_intention, background_coupon_name, has_coupon, json_data, customer_id)
    try:
        with postgre_sql.get_resource() as (cursor, conn):
            cursor.execute(f"insert into public.wechat_user_info (wx_id, agent_id, username, sex, remaining_balance, credit_balance,loan_intention, background_coupon_name, has_coupon, json_data, customer_id)"
                           f" values (%s, %s, %s ,%s, %s, %s, %s ,%s, %s, %s, %s) "
                           # f"on conflict (wx_id) do update set user_info = '{userInfo}'"
                           , val)
            logging.info(f"插入用户信息成功 wx_id:{wx_id} agent_id:{agent_id}")
    except:
        logging.info(f"插入用户信息失败, 准备重试 wx_id:{wx_id} agent_id:{agent_id}")
        with postgre_sql.get_resource() as (cursor, conn):
            cursor.execute(f"insert into public.wechat_user_info (wx_id, agent_id, username, sex, remaining_balance, credit_balance,loan_intention, background_coupon_name, has_coupon, json_data, customer_id)"
                           f" values (%s, %s, %s ,%s, %s, %s, %s ,%s, %s, %s, %s) "
                           # f"on conflict (wx_id) do update set user_info = '{userInfo}'"
                           , val)
        logging.info(f"重试插入用户信息成功 wx_id:{wx_id} agent_id:{agent_id}")


# 获取用户优惠券信息
# def get_user_coupon_info(wx_id):
#     s = get_user_info(wx_id)
#     if s is None:
#         return None
#     return json.loads(s).get("coupon", None)


# def user_has_coupon(wx_id):
#     coupon_list = get_user_coupon_info(wx_id)
#     has_coupon = coupon_list is not None and coupon_list != []
#     info = get_user_info_dict(wx_id)
#     has_coupon_tag = info["tag"].get("用户是否有金条优惠券", "{否}") == "{是}"
#     return has_coupon or has_coupon_tag


def user_has_coupon(wx_id):
    result = get_user_info_dict(wx_id)
    background_coupon_name = result.get("background_coupon_name", None)
    has_coupon = result.get("has_coupon", None)
    logging.info(f"查询用户优惠券信息 wx_id:{wx_id} background_coupon_name:{background_coupon_name} has_coupon:{has_coupon}")
    return background_coupon_name is not None or has_coupon == "{是}"


# 判断是否为大额用户
# def user_has_big_balance(wx_id):
#     info = get_user_info_dict(wx_id)
#     balance = info["tag"].get("金条剩余额度_实时", "0")
#     return balance == "50000-100000" or balance == "100000+"


def user_has_big_balance(wx_id):
    result = get_user_info_dict(wx_id)
    balance = result.get("remaining_balance", None)
    can_credit = get_can_credit(result)
    logging.info(f"查询用户剩余额度 wx_id:{wx_id} balance:{balance} can_credit:{can_credit}")
    return (balance == "20000-50000" or balance == "50000-100000" or balance == "100000+") and can_credit


def get_can_credit(result):
    json_data = result.get("json_data", None)
    if json_data is not None:
        json_data = json.loads(json_data)
        can_credit = json_data.get('tag', {}).get("金条已激活可用信用户", None)
        return can_credit == "是"
    else:
        return False


def check_coupon(user_info: dict):
    coupons = user_info.get("coupon")
    if coupons:
        activity_name = coupons[0]["activityName"]
        if activity_name not in exist_coupon:
            logging.warning(f"出现新的优惠券:{activity_name}")


def get_coupon_name(wx_id):
    user_info = get_user_info_dict_redis(wx_id)
    coupon = user_info.get('coupon')
    if coupon:
        background_coupon_name = coupon[0].get('activityName')
    else:
        background_coupon_name = None
    return background_coupon_name


# def save_user_info_to_db():
#     global keys, wx_id, ttl
#     keys = tair_util.keys("QW:UserInfo:*")
#     i = 0
#     total = 0
#     with open("wx_id_list.txt", "r") as f:
#         wx_id_list = set(f.read().split("\n"))
#     # print(len(wx_id_list))
#     local_wx_id_list = set()
#     for key in keys:
#         wx_id = key.split("QW:UserInfo:")[1]
#         if wx_id in wx_id_list:
#             i += 1
#             logging.info(f"i = {i} wx_id:{wx_id} 已经存在")
#             continue
#         total += 1
#         local_wx_id_list.add(wx_id)
#         user_info = get_user_info_dict(wx_id)
#         ttl = tair_util.tair.ttl(f"QW:UserInfo:{wx_id}")
#         time_ttl = 30 * 3600 * 24 - ttl
#         t = time.time()
#         da = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t - time_ttl))
#         logging.info(f"total:{total} wx_id:{wx_id} date:{da}")
#         set_user_info(wx_id, None, user_info, da)
#         if total % 10 == 0:
#             logging.info("把100个wx_id写入文件")
#             with open("wx_id_list.txt", "a") as f:
#                 f.write("\n".join(local_wx_id_list))
#                 f.writelines("\n")
#             local_wx_id_list = set()
#     logging.info(f"i:{i} total:{total}")


if __name__ == "__main__":
    user_info = {'coupon': [{'activityId': '9231116090722625945', 'activityName': '30天免息券（31-61天免息）', 'activityAlias': '11月30天免息券（31-61天免息）', 'activityStatus': 'OL', 'activityStatusDes': '', 'activityTakeStatus': 'TS001', 'activityTakeStatusDes': '可领', 'awardName': '30天免息券', 'awardsType': 'SP', 'awardsTypeDes': '单个奖品', 'prizeName': '30天免息券', 'assignedAmount': '500.00', 'assignedAmountBD': 500.0, 'discountAmount': '0', 'discountAmountBD': 0, 'appLink': None, 'useChannel': 1, 'useChannelDes': '企微'}], 'tag': {'金条三方offer降息用户': '未知', '金条CDS0风险未激活黑名单用户': '未知', '金条已激活可用信用户': '是', '金条本金营销黑名单': '未知', '金条风控黑名单': '未知', '金条拒贷黑名单': '未知', '是否京东员工': '未知', '是否登陆过金融app': '是', '性别': '男', '年龄分段': '26-35岁', '收入预测': '高', '客户风险测评等级': '保守型', '金条PLUS激活状态': '未知', '金条生命周期描述': 'g流失期-80天外', '消金企微末次群发距今天数分段': '[15,20]', '金条借贷意向': '高意向', '主动提额资格': '符合要求', '金条末次提额时间距今天数': '12', '金条末次降息开始时间': '2023-12-01 11:46:10', '金条末次提额时间': '2023-12-08 17:20:14', '金条高潜用户': '未知', '近60天金条相关产品浏览时长': '未知', '近60天金条相关产品点击次数': '未知', '金条激活类型': '开新', '金条激活天数': '361天以上', '金条授信额度档位': '(20000,+∞)', '菁卡一卡已核卡未激活用户': '未知', '金条是否激活首贷': '金条已首贷用户', '是否降价客户': '是', '金条-是否降价客户': '是', '用户是否有金条优惠券': '{否}', '用户是否有金条贴息券': None, '金条-授信额度': None, '金条激活首贷状态': '[已激活已首贷]', '转化预测': None, '距离金条已复贷天数_组合': None, '金条剩余额度_实时': '50000-100000', '金条授信额度_实时': '{50000+}', '金条交易拒绝_组合': None, '距离金条已首贷天数_组合': '{180天以上}', '金条-降息开始时间': None, '金条-降息结束时间': None, '金条-点击借钱时间': None, '金条1元试借时间': None, '金条-是否首贷': None, '金条-是否激活': None, '金条-提额时间': None, '填表页首页提交时间': None, '进件时间': None, '菁卡当日进件人群（实时）': None, '金条首贷用户（实时）': None, '金条用户开户分类（实时）': None, '金条激活用户（实时）': None, '当日金条被拒交易被拒用户': None, '金条当日借款成功': None, '近7天固定提额提醒策略': None, '近7天临时提额提醒策略': None, '近7天金条止付回捞策略': None, '近7天三方offer策略': None, '近7天三方offer断点策略': None, '近7天优惠券到账提醒策略': None, '近7天优惠券到期提醒策略': None, '近7天降息提醒策略': None, '近7天还款提醒策略': None, '近7天金条浏览断点策略': None, '近7天已加微T30外兜底策略': None, '近7天新加微T30内兜底策略': None}, 'username': '侯**'}
    # check_coupon(user_info)
    # set_user_info("wmTT-TEAAAU8y2LGG_hr4DFGi_HMnypw3", None, user_info)
    print(user_has_coupon("wmTT-TEAAAHc20cQFqqSqwkOpOfSNvuAq"))
    user_info = get_user_info_dict('wmTT-TEAAAHc20cQFqqSqwkOpOfSNvuA1')
    print(user_info.get("sex"))
    print(user_info.get("json_data"))

    # print(get_user_info("wmTT-TEAAAicVQT-rANWu_HSzyNAIGcA"))
    print(user_has_big_balance("wmsPklSgAA8wLlnORhjlz0cr84v1DOvg"))
    # save_user_info_to_db()

